package com.efa.backend.base.listener;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class HsqlListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = this.getConnection();
			stmt = conn.createStatement();
			stmt.executeUpdate("SHUTDOWN;");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
				}
				stmt = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = this.getConnection();
			stmt = conn.createStatement();
			BufferedReader br = new BufferedReader(new FileReader(this
					.getClass().getResource("").getPath()
					+ "/backend.sql"));
			String readLine = "";
			List<String> lineList = new ArrayList<String>();
			while ((readLine = br.readLine()) != null) {
				lineList.add(readLine);
			}
			br.close();
			List<String> sqlList = new ArrayList<String>();
			String tempStr = "";
			boolean flag = false;
			for (String line : lineList) {
				if (line.trim().length() <= 0) {
					continue;
				}
				if (line.startsWith("--adddata")) {
					sqlList.add(tempStr);
					flag = true;
					continue;
				}
				if (flag) {
					sqlList.add(line);
					continue;
				}
				if (line.startsWith("--")) {
					if (tempStr != "") {
						sqlList.add(tempStr);
						tempStr = "";
					}
				} else {
					tempStr += line;
				}
			}
			for (String sqlStr : sqlList) {
				stmt.executeUpdate(sqlStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
				}
				stmt = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
				conn = null;
			}
		}
	}

	private Connection getConnection() throws Exception {
		Class.forName("org.hsqldb.jdbcDriver");
		return DriverManager.getConnection("jdbc:hsqldb:mem:efa", "SA", "");
	}

}
